package com.ktgj.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.domain.R;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.pay.mapper.DeliveryMapper;
import com.ktgj.pay.mapper.InvoiceMapper;
import com.ktgj.pay.mapper.OperateLogMapper;
import com.ktgj.pay.service.IInvoiceDeliveryService;
import com.ktgj.pay.service.IInvoiceInvoiceOrderService;
import com.ktgj.pay.service.IInvoiceOperatelogService;
import com.ktgj.pay.service.InvoiceInterFaceService;
import com.ktgj.pay.utils.BaseUtil;
import com.ktgj.pay.utils.Log4j;
import com.ktgj.pay.utils.MailUtil;
import com.ktgj.pay.utils.SendInvoiceInterfaceUtil;
import com.ktgj.pay.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;


@Service("invoiceInterFaceService")
public class InvoiceInterFaceServiceImpl implements InvoiceInterFaceService {
	
	@Autowired
	MailUtil mailUtil;
	
	@Autowired
	IInvoiceDeliveryService deliveryService;
	
	@Autowired
	IInvoiceOperatelogService operatelogService;
	
	@Autowired
	InvoiceMapper invoiceMapper;

	@Autowired
	RemoteCustomerService customerService;

	@Autowired
	IInvoiceInvoiceOrderService invoiceOrderService;
	
	@Override
	public MoInterfaceResponse invoiceFPKJ(Long orderId, String Json) {
		
		/**
		 * 构建内层xml字符串-并base64加密返回
		 */
		MoFPKJRequest request = SendInvoiceInterfaceUtil.getFPKJRequest(Json);//解析Json，封装为对象返回
		String xml = SendInvoiceInterfaceUtil.getFPKJRequestXml(request);//解析对象，返回XmlString
		String context = BaseUtil.Encoded(xml);
		/**
		 * 测试数据 -- 发票基类
		 */
//		String context = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHJlcXVlc3RGUEtKPgogIDxzd25vPjE1NjE2NTUwP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pbElkZW50aWZpY2F0aW9uPgogIDxrcFR5cGU+MDwva3BUeXBlPgogIDxpdGVtcz4KICAgIDxpdGVtPgogICAgICA8Z29vZHNOYW1lPuacuuelqOasvjwvZ29vZHNOYW1lPgogICAgICA8bGluZVR5cGU+MDwvbGluZVR5cGU+CiAgICAgIDxsaW5lQ29kZT4xPC9saW5lQ29kZT4KICAgICAgPG1vZGVsPjwvbW9kZWw+CiAgICAgIDx1bml0PjwvdW5pdD4KICAgICAgPHF0eT48L3F0eT4KICAgICAgPHByaWNlPjwvcHJpY2U+CiAgICAgIDx0YXhQcmljZT48L3RheFByaWNlPgogICAgICA8YW1vdW50PjwvYW1vdW50PgogICAgICA8dGF4QW1vdW50PjYwMC4wMDwvdGF4QW1vdW50PgogICAgICA8dGF4PjwvdGF4PgogICAgICA8dGF4UmF0ZT4wLjA2PC90YXhSYXRlPgogICAgICA8dGF4Q29kZT4zMDcwMzAxPC90YXhDb2RlPgogICAgICA8dGF4UHJlPjA8L3RheFByZT4KICAgICAgPHRheFByZWNvbj48L3RheFByZWNvbj4KICAgICAgPHplcm9UYXg+PC96ZXJvVGF4PgogICAgICA8Z3JvcEdvb2RzTm8+PC9ncm9wR29vZHNObz4KICAgICAgPHRheERlZHVjdGlvbj48L3RheERlZHVjdGlvbj4KICAgICAgPHRheFZlcnNpb24+MzAuMDwvdGF4VmVyc2lvbj4KICAgIDwvaXRlbT4KICA8L2l0ZW1zPgo8L3JlcXVlc3RGUEtKPg==";
		/**
		 * 包装请求xml字符串
		 */
		String result = BaseUtil.returnRequestString("EISP.FPKJ",context,request.getSellerTaxNo());
		/**
		 * 正式逻辑
		 */
		MoInterfaceResponse interfaceResponse = new MoInterfaceResponse();
		String responseString = "";
		try {
			/*
			 * 发送请求-返回接口数据字符串
			 */
			responseString = SendInvoiceInterfaceUtil.sendInvoice(result);
		} catch (IOException e) {
			e.printStackTrace();
			Log4j.addErrorLog(e.getMessage(), "EISP.FPKJ");
		}
		if(responseString.equals("false")){
			interfaceResponse.setSign(false);
			Log4j.addLog("EISP.FPKJ", xml, "请求失败无返回");
		}else{
			/*
			 * 解析返回的字符串为对象实体
			 */
			MoResponse responseObject = SendInvoiceInterfaceUtil.getResponseXmlInfo(responseString);
			/*
			 * 根据对象实体-构建对应接口的返回数据
			 */
			Object object = SendInvoiceInterfaceUtil.getFPKJResult(responseObject.getExData().getContent());
			interfaceResponse = BaseUtil.getResponse(responseObject,object);
			interfaceResponse.setSign(true);
			Log4j.addLog("EISP.FPKJ", xml, BaseUtil.Decide(responseObject.getExData().getContent()));

			if (interfaceResponse.getReturnCode().equals("1000")) {
				InvoiceInvoiceOrder invoiceOrder = new InvoiceInvoiceOrder();
				JSONObject JSR = JSONObject.parseObject(Json);
				InvoiceInterFace invoiceInterFace = JSON.parseObject(Json, InvoiceInterFace.class);
				invoiceOrder.setInvoiceid(String.valueOf(JSR.getLong("swno")));
				invoiceOrder.setJsjid(String.valueOf(orderId));
				invoiceOrder.setOrdernum(JSR.getString("swno"));
				invoiceOrder.setSuborders(JSR.getString("suborders"));
				invoiceOrder.setState(4L);
				invoiceOrder.setType(2L);
				invoiceOrder.setSort(2L);
				invoiceOrder.setHaveitinerary(2L);
				invoiceOrder.setRemark(JSR.getString("invMemo"));
				invoiceOrder.setSellertitle(JSR.getString("custName"));
				invoiceOrder.setSellertaxno(JSR.getString("sellerTaxNo"));
				String sellerAddrPhone = JSR.getString("sellerAddrPhone");
				if (sellerAddrPhone != null) {
					String[] split = sellerAddrPhone.split(" ");
					invoiceOrder.setSelleraddress(split[0]);
					invoiceOrder.setSellerphone(split[1]);
				}
				invoiceOrder.setSellerbankaccount(JSR.getString("sellerBankAccount"));
				invoiceOrder.setSourceway(JSR.getLong("sourceWay"));
				invoiceOrder.setGoodsname(invoiceInterFace.getItems().get(0).getGoodsName());
				invoiceOrder.setSourceappid(JSR.getLong("sourceAppID"));
				invoiceOrder.setTaxamount(new BigDecimal(invoiceInterFace.getItems().get(0).getTaxAmount()));
				invoiceOrder.setTaxrate(JSR.getBigDecimal("taxRate"));
				invoiceOrder.setTaxcode(invoiceInterFace.getItems().get(0).getTaxCode());
				invoiceOrder.setCreateTime(new Date());
				invoiceOrderService.insertInvoiceInvoiceOrder(invoiceOrder);

				InvoiceDelivery delivery = new InvoiceDelivery();
				delivery.setDeliverytype(2L);
				delivery.setExpressdeliverystate(1L);
				delivery.setEmailstate(1L);
				delivery.setInvoiceid(JSR.getString("swno"));
				deliveryService.insertInvoiceDelivery(delivery);
			}

		}
		return interfaceResponse;
	}

	@Override
	public MoInterfaceResponse invoiceFPXZ(String Json,String path) {
		JSONObject JSR = JSONObject.parseObject(Json);
		Long swno = JSR.getLong("swno");
		InvoiceInvoiceOrder invoiceOrderById = invoiceOrderService.selectInvoiceInvoiceOrderByNum(swno);
		MoInterfaceResponse interfaceResponse = new MoInterfaceResponse();
		if (invoiceOrderById.getImgurl() != null && !invoiceOrderById.getImgurl().equals("")) {
			interfaceResponse.setReturnMessage("发票已下载！" + "路径：" + invoiceOrderById.getImgurl());
		} else {
			/**
			 * 构建内层xml字符串-并base64加密返回
			 */
			MoFPXZRequest request = SendInvoiceInterfaceUtil.getFPXZRequest(Json);
			String xml = SendInvoiceInterfaceUtil.getFPXZRequestXml(request);
			String context = BaseUtil.Encoded(xml);
			/**
			 * 包装请求xml字符串
			 */
			String result = BaseUtil.returnRequestString("EISP.FPXZ",context,request.getSellerTaxNo());
			/**
			 * 正式逻辑
			 */

			String responseString = "";
			try {
				/*
				 * 发送请求-返回接口数据字符串
				 */
				responseString = SendInvoiceInterfaceUtil.sendInvoice(result);
			} catch (IOException e) {
				e.printStackTrace();
				Log4j.addErrorLog(e.getMessage(), "EISP.FPXZ");
			}
			if(responseString.equals("false")){
				interfaceResponse.setSign(false);
				Log4j.addLog("EISP.FPXZ", xml, "请求失败无返回");
			}else{
				/*
				 * 解析返回的字符串为对象实体
				 */
				MoResponse responseObject = SendInvoiceInterfaceUtil.getResponseXmlInfo(responseString);
				/*
				 * 根据对象实体-构建对应接口的返回数据
				 */
				Object object = SendInvoiceInterfaceUtil.getFPXZResult(responseObject.getExData().getContent(),path);
				interfaceResponse = BaseUtil.getResponse(responseObject,object);
				interfaceResponse.setSign(true);
				Log4j.addLog("EISP.FPXZ", xml, BaseUtil.Decide(responseObject.getExData().getContent()));

				if (interfaceResponse.getReturnCode().equals("2000")) {
					InvoiceInvoiceOrder invoiceOrder = new InvoiceInvoiceOrder();
					MoFPXZResponse fpxzResult = SendInvoiceInterfaceUtil.getFPXZResult(responseObject.getExData().getContent(), path);
					for (MoFPXZInvoiceInfo info : fpxzResult.getInfos()) {
						invoiceOrder.setInvoiceid(fpxzResult.getSwno());
						invoiceOrder.setImgurl(info.getPdfContent());
						invoiceOrderService.updateInvoiceInvoiceOrder(invoiceOrder);
					}

				}
			}
		}
		return interfaceResponse;
	}

	@Override
	public MoInterfaceResponse invoiceFPCH(String Json) {
		/**
		 * 构建内层xml字符串-并base64加密返回
		 */
		MoFPCHRequest request = SendInvoiceInterfaceUtil.getFPCHRequest(Json);
		String xml = SendInvoiceInterfaceUtil.getFPCHRequestXml(request);
		String context = BaseUtil.Encoded(xml);
		/**
		 * 包装请求xml字符串
		 */
		String result = BaseUtil.returnRequestString("EISP.FPCH",context,request.getSellerTaxNo());
		/**
		 * 正式逻辑
		 */
		MoInterfaceResponse interfaceResponse = new MoInterfaceResponse();
		String responseString = "";
		try {
			/*
			 * 发送请求-返回接口数据字符串
			 */
			responseString = SendInvoiceInterfaceUtil.sendInvoice(result);
		} catch (IOException e) {
			e.printStackTrace();
			Log4j.addErrorLog(e.getMessage(), "EISP.FPCH");
		}
		if(responseString.equals("false")){
			interfaceResponse.setSign(false);
			Log4j.addLog("EISP.FPCH", xml, "请求失败无返回");
		}else{
			/*
			 * 解析返回的字符串为对象实体
			 */
			MoResponse responseObject = SendInvoiceInterfaceUtil.getResponseXmlInfo(responseString);
			/*
			 * 根据对象实体-构建对应接口的返回数据
			 */
			Object object = SendInvoiceInterfaceUtil.getFPCHResult(responseObject.getExData().getContent());
			interfaceResponse = BaseUtil.getResponse(responseObject,object);
			interfaceResponse.setSign(true);
			Log4j.addLog("EISP.FPCH", xml, BaseUtil.Decide(responseObject.getExData().getContent()));
		}
		return interfaceResponse;
	}

	@Override
	public MoInterfaceResponse invoiceFPYLCX(String Json) {
		MoFPYLCXRequest request = SendInvoiceInterfaceUtil.getFpylcxRequest(Json);
		String xml = SendInvoiceInterfaceUtil.getFpylcxRequestXml(request);
		String context = BaseUtil.Encoded(xml);
		String result = BaseUtil.returnRequestString("EISP.FPYLCX",context,request.getSellerTaxNo());
		/**
		 * 正式逻辑
		 */
		MoInterfaceResponse interfaceResponse = new MoInterfaceResponse();
		String responseString = "";
		try {
			/*
			 * 发送请求-返回接口数据字符串
			 */
			responseString = SendInvoiceInterfaceUtil.sendInvoice(result);
		} catch (IOException e) {
			e.printStackTrace();
			Log4j.addErrorLog(e.getMessage(), "EISP.FPYLCX");
		}
		if(responseString.equals("false")){
			interfaceResponse.setSign(false);
			Log4j.addLog("EISP.FPYLCX", xml, "请求失败无返回");
		}else{
			/*
			 * 解析返回的字符串为对象实体
			 */
			MoResponse responseObject = SendInvoiceInterfaceUtil.getResponseXmlInfo(responseString);
			/*
			 * 根据对象实体-构建对应接口的返回数据
			 */
			Object object = SendInvoiceInterfaceUtil.getFPYLCXResult(responseObject.getExData().getContent());
			interfaceResponse = BaseUtil.getResponse(responseObject,object);
			interfaceResponse.setSign(true);
			Log4j.addLog("EISP.FPYLCX", xml, BaseUtil.Decide(responseObject.getExData().getContent()));
		}
		
		return interfaceResponse;
	}

	@Override
	public MoInterfaceResponse invoiceDDSC(String Json) {
		MoDDSCRequest request = SendInvoiceInterfaceUtil.getDDSCRequest(Json);
		String xml = SendInvoiceInterfaceUtil.getDDSCRequestXml(request);
		String context = BaseUtil.Encoded(xml);
		String result = BaseUtil.returnRequestString("EISP.DDSC",context,request.getSellerTaxNo());
		/**
		 * 正式逻辑
		 */
		MoInterfaceResponse interfaceResponse = new MoInterfaceResponse();
		String responseString = "";
		try {
			/*
			 * 发送请求-返回接口数据字符串
			 */
			responseString = SendInvoiceInterfaceUtil.sendInvoice(result);
		} catch (IOException e) {
			e.printStackTrace();
			Log4j.addErrorLog(e.getMessage(), "EISP.DDSC");
		}
		if(responseString.equals("false")){
			interfaceResponse.setSign(false);
			Log4j.addLog("EISP.DDSC", xml, "请求失败无返回");
		}else{
			/*
			 * 解析返回的字符串为对象实体
			 */
			MoResponse responseObject = SendInvoiceInterfaceUtil.getResponseXmlInfo(responseString);
			/*
			 * 根据对象实体-构建对应接口的返回数据
			 */
			Object object = SendInvoiceInterfaceUtil.getDDSCResult(responseObject.getExData().getContent());
			interfaceResponse = BaseUtil.getResponse(responseObject,object);
			interfaceResponse.setSign(true);
			Log4j.addLog("EISP.DDSC", xml, BaseUtil.Decide(responseObject.getExData().getContent()));
		}
		
		return interfaceResponse;
	}

	@Override
	public MoSendMail sendStoreAlertMail(String Json, String path ) {
		MoSendMail sendMail = getSendMailNew(Json, path);
		try {
			// 发送邮件
			mailUtil.sendMail(sendMail);
			sendMail.setSend(true);
			/*
			 * 回填配送记录
			 */
			InvoiceDelivery delivery = new InvoiceDelivery();
			delivery.setInvoiceid(sendMail.getInvoiceId());
			delivery.setEmailstate(3L);
			delivery.setEmail(sendMail.getToAddress());
			delivery.setDeliverytime(new Date());
			deliveryService.updateInvoiceDeliverys(delivery);
			/*
			 * 添加操作记录
			 */
			InvoiceOperatelog operateLog = new InvoiceOperatelog();
			operateLog.setInvoiceid(Long.valueOf(sendMail.getInvoiceId()));
			operateLog.setOperater("系统管理员");
			operateLog.setOperatertime(new Date());
			operateLog.setOperaterdesc("电子发票邮件-"+sendMail.getToAddress()+"发送成功");
			operatelogService.insertInvoiceOperatelog(operateLog);
		} catch (MessagingException e) {
			e.printStackTrace();
			sendMail.setSend(false);
			Log4j.addErrorLog(e.getMessage(), "sendStoreAlertMail");
		}
		return sendMail;
	}
	
	
	
	public MoSendMail getSendMailNew(String Json,String path){
		MoSendMail sendMail = new MoSendMail();
		JSONObject JSR = JSONObject.parseObject(Json);
		sendMail.setContainFJ(JSR.getBoolean("isContainFJ"));
		if(sendMail.isContainFJ()){
			sendMail.setFileName(JSR.getString("fileName"));
//			sendMail.setFilePath(path+"\\"+sendMail.getFileName());
			sendMail.setFilePath(path+"/"+sendMail.getFileName());
		}
		sendMail.setToAddress(JSR.getString("toAddress").toLowerCase().trim());
		sendMail.setSend(false);
		sendMail.setInvoiceId(JSR.getString("invoiceId"));
		
		
		MoInvoice invoice = invoiceMapper.getInvoice(Long.valueOf(sendMail.getInvoiceId()), "", "");
		String title = "金色世纪-电子发票开具通知";
		sendMail.setTitle(title);
		String context = "";
		if(invoice != null){
			context = getContextModel(JSR.getIntValue("sourceWay"),invoice);
		}
		sendMail.setContext(context);
		
		
		return sendMail;
	}
	
	
	public String getContextModel(int sourceWay,MoInvoice invoice){
		String context = "";
		switch (sourceWay) {
		case 1:
			context = "尊敬的金色世纪用户："+"\n"+" 您于"
					+ BaseUtil.dateToString(invoice.getCreateTime().getTime(),"yyyy-MM-dd") + "申请的电子发票已开具，发票编号"
					+ invoice.getOriginalInvoiceCode() + "-" + invoice.getOriginalInvoiceNo() + "，金额"
					+ invoice.getTaxAmount()+"元，请点击附件下载。\n电子发票为国家法定发票格式，具体报销流程请咨询您所在公司的财务部门。\n24小时客服热线：400-810-1688";
			break;
		case 2:
			
			break;
		case 3:
			
			break;

		default:
			break;
		}
		return context;
	}
	
	

}
